import 'dart:convert' as convert;

import 'package:flutter_bili_app/http/core/hi_net_adapter.dart';
import 'package:flutter_bili_app/http/core/hi_net_error.dart';
import 'package:flutter_bili_app/http/request/basic_request.dart';
import 'package:http/http.dart' as http;

///dio适配器
class HttpAdapter extends HiNetAdapter {
  @override
  Future<HiNetResponse<T>> send<T>(BaseRequest request) async {
    var response, header = Map<String, String>.from(request.header);
    var error;
    Uri url = Uri.parse(request.url());
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        response = await http.get(url, headers: header);
      } else if (request.httpMethod() == HttpMethod.POST) {
        response = await http.post(url, headers: header, body: request.params);
      } else if (request.httpMethod() == HttpMethod.DELETE) {
        response =
            await http.delete(url, headers: header, body: request.params);
      }
    } on Error catch (e) {
      error = e;
      response = e.toString();
    }
    if (error != null) {
      print(buildRes(response, request));
      var data = buildRes(response, request);

      ///抛出HiNetError
      print(buildRes(response, request));
      throw HiNetError(response?.statusCode ?? -1, error.toString(),
          data: data);
    }
    return buildRes(response, request);
  }

  ///构建HiNetResponse
  HiNetResponse buildRes(response, BaseRequest request) {
    Map<String, dynamic> responseData =
        convert.jsonDecode(String.fromCharCodes(response?.bodyBytes));
    return HiNetResponse(
        data: responseData["data"],
        request: request,
        statusCode: response?.statusCode,
        statusMessage: responseData["msg"],
        extra: response);
  }
}
